package com.runachina.runa;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.runachina.R;
import com.runachina.common.BaseActivity;
import com.runachina.common.CompanyActivity;
import com.runachina.java.SendDataAnalysis;
import com.runachina.java.TcpSocket;

import java.util.Timer;
import java.util.TimerTask;

public class SetAttributeActivity extends BaseActivity implements OnClickListener{


    private Button setbtn;
    private TextView sendtitle,sendtext;
    public  static TextView rcvtext,rcvbyte;
    private RadioGroup  water,unit,hot,type;
    private RadioButton inwater,backwater;
    private RadioButton unitkw,unitjj;
    private RadioButton singlehot,coldhot;
    private RadioButton type188,typemodbus;
    private EditText uartrate;


    private Button btnCheck;
    private EditText edtCheck;

    private static byte [] modifyAttr = {(byte) 0xfe,(byte) 0xfe,(byte) 0xfe, (byte) 0xfe,(byte) 0xfe,
            0x68, 0x20,
            (byte) 0xAA,(byte) 0xAA,(byte) 0xAA,(byte) 0xAA, (byte) 0xAA,(byte) 0xAA,(byte) 0xAA,
            0x04, 0x05,0x39,(byte) 0xA0,(byte) 0x88,
            0x00, 0x04,
            (byte) 0x9c, 0x16,
            (byte)0x00,0x16};
    //fe fe fe fe fe 68 20 aa aa aa aa aa aa aa 04 05 53 a0 89 00 00 b3 16无返回
    private static byte[] modifyCheck={(byte) 0xfe,(byte) 0xfe,(byte) 0xfe, (byte) 0xfe,(byte) 0xfe,
            0x68,0x20,
            (byte) 0xAA,(byte) 0xAA,(byte) 0xAA,(byte) 0xAA, (byte) 0xAA,(byte) 0xAA,(byte) 0xAA,
            0x04,0x05,0x53,(byte) 0xa0,(byte) 0x89,
            0x00,//19
            0x00,(byte)
            0xb3,//21
            0x16,(byte)0x00,0x16};


    private int attrResult=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_setatribute);

        set_toolbar("仪表属性", "");

        set_leftmenu(SetAttributeActivity.this);

        init_RadioButton();

        init_view();

        hideSendText(sendtitle,sendtext);
        inWhichAc="runa.SetAttributeActivity";
    }

    private void init_view(){
        setbtn =(Button) findViewById(R.id.setbtn);
        setbtn.setOnClickListener(sebtnFun);
        sendtitle=(TextView)findViewById(R.id.sendtitle);
        sendtext=(TextView) findViewById(R.id.sendtext);
        rcvtext =(TextView) findViewById(R.id.rcvtext);
        rcvbyte=(TextView) findViewById(R.id.rcvbyte);
        uartrate=(EditText) findViewById(R.id.uartrate);
        btnCheck=(Button) findViewById(R.id.btn_check);
        btnCheck.setOnClickListener(btnCheckFun);

        edtCheck=(EditText) findViewById(R.id.edt_check);
    }

    /**
     * 设置校验button
     */
    View.OnClickListener btnCheckFun =new OnClickListener() {
        @Override
        public void onClick(View v) {

            //inWhichAc="runa.SetAttributeActivity.check";
            String checkStr=edtCheck.getText().toString()+"";
            if (!checkStr.isEmpty()){
                clear_textDisplay();

                if(checkStr.equals("0")){
                    modifyCheck[19]=0x00;
                    modifyCheck[21]=(byte)0xb3;
                }else if(checkStr.equals("1")){
                    modifyCheck[19]=0x02;
                    modifyCheck[21]=(byte)0xb5;
                }else if(checkStr.equals("2")){
                    modifyCheck[19]=0x01;
                    modifyCheck[21]=(byte)0xb4;
                }
                byte[] sendbyte= SendDataAnalysis.setAttr(modifyCheck);
                //显示完整的发送sendbyte[]
                sendtext.setText(byteToHexString(sendbyte));

                System.out.println(">>"+byteToHexString(sendbyte));
                //发送sendbyte[]
                String sendResult = TcpSocket.wifiSendByte(sendbyte);
//                new Timer().schedule(new TimerTask()    {
//                    @Override
//                    public void run() {
//                        TcpSocket.receServerMessage();
//                    }
//                },3000);
            }else {
                show("请设置校验方式 !");
            }
        }
    };

    /**
     * 设置属性button
     */
    View.OnClickListener sebtnFun =new OnClickListener() {
        @Override
        public void onClick(View v) {

            //inWhichAc="runa.SetAttributeActivity";
            //校验和
            modifyAttr[19] =(byte)attrResult;
            if(getUartRate()!=0)
            {
                clear_textDisplay();
                modifyAttr[20] =(byte) getUartRate();
                modifyAttr[21] =(byte)(modifyAttr[19]+modifyAttr[20]+(byte)0x98  );
                byte[] sendbyte= SendDataAnalysis.setAttr(modifyAttr);
                //显示完整的发送sendbyte[]
                sendtext.setText(byteToHexString(sendbyte));
                //发送sendbyte[]
                String sendResult = TcpSocket.wifiSendByte(sendbyte);
//                new Timer().schedule(new TimerTask() {
//                    @Override
//                    public void run() {
//                        TcpSocket.receServerMessage();
//                    }
//                },3000);
            }else{
                show("波特率出错 !");
            }
        }
    };


    private int getUartRate(){
        int uart = Integer.parseInt("0"+uartrate.getText().toString());
        switch (uart){
            case 300:
                uart= 1;return uart;
            case 600:
                uart= 2;return uart;
            case 1200:
                uart= 3;return uart;
            case 2400:
                uart= 4;return uart;
            case 4800:
                uart= 5;return uart;
            case 9600:
                uart= 6;return uart;
            default:
                uart= 0;return uart;//出错
        }

    }

    public void clear_textDisplay(){
        sendtext.setText("");
        rcvtext.setText("");
        rcvbyte.setText("");
        startTimer(TI);
    }

    private void init_RadioButton(){
        inwater =(RadioButton)findViewById(R.id.inwater);
        inwater.setOnClickListener(this);
        backwater=(RadioButton)findViewById(R.id.backwater);
        backwater.setOnClickListener(this);

        unitkw=(RadioButton)findViewById(R.id.unitkw);
        unitkw.setOnClickListener(this);
        unitjj=(RadioButton)findViewById(R.id.unitjj);
        unitjj.setOnClickListener(this);

        singlehot=(RadioButton)findViewById(R.id.singlehot);
        singlehot.setOnClickListener(this);
        coldhot=(RadioButton)findViewById(R.id.coldhot);
        coldhot.setOnClickListener(this);

        type188=(RadioButton)findViewById(R.id.type188);
        type188.setOnClickListener(this);
        typemodbus=(RadioButton)findViewById(R.id.typemodbus);
        typemodbus.setOnClickListener(this);


    }

    /**
     * radioButton判断
     * @param v
     */
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.inwater:
                attrResult = (attrResult & 0xFE) ;//0000 0001--0x1
                break;
            case R.id.backwater:
                attrResult = (attrResult | 0x01) ;
                break;
            case R.id.unitkw:
                attrResult = (attrResult & 0xF7) ;//0000 1000--0x8
                break;
            case R.id.unitjj:
                attrResult = (attrResult | 0x08) ;
                break;
            case R.id.singlehot:
                attrResult = (attrResult & 0xFB) ;//0000 0100--0x4
                break;
            case R.id.coldhot:
                attrResult = (attrResult | 0x04) ;
                break;
            case R.id.type188:
                attrResult = (attrResult & 0xDF) ;//0010 0000--0x20
                break;
            case R.id.typemodbus:
                attrResult = (attrResult | 0x20) ;
                break;
            default:
                break;
        }
    }


    /**
     * Toolbar中的Menu菜单项
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    /**
     * Activity创建时候会执行一次，所以可以用来初始化toolbar中的wifi图标
     * @return
     */
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);

        MenuItem menuItem = menu.findItem(R.id.menu_connect);
        //wifi connect，返回当前连接状态
        String connectResult= TcpSocket.readConnect();
        if((connectResult.equals("连接成功!"))||connectResult.equals("已经连接!")){
            menuItem.setTitle("connect!");
            menuItem.setIcon(R.drawable.wifi_connect);
        }else{
            menuItem.setTitle("no connect!");
            menuItem.setIcon(R.drawable.wifi_noconnect);
        }
        return true;
    }private MenuItem me;
    private int t_type=0;
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        me=item;
        System.out.println("onOptionsItemSelected");

        switch (item.getItemId()){
            case R.id.menu_connect:
                String connectResult= TcpSocket.wificonnect();//wifi connect
                show(connectResult);//TOast connect result
                if((connectResult.equals("连接成功!"))||connectResult.equals("已经连接!")){
                    item.setTitle("connect!");
                    item.setIcon(R.drawable.wifi_connect);
                }else{
                    item.setTitle("no connect!");
                    item.setIcon(R.drawable.wifi_noconnect);
                    new Timer().schedule(new TimerTask() {
                        @Override
                        public void run() {
                            goWifiSetting();
                            t_type=1;
                        }
                    },1000);
                }
                return true;
            case R.id.menu_choice:
                intent = new Intent(SetAttributeActivity.this, CompanyActivity.class);
                startActivity(intent);
                finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    //每次进来判断是否是从设置wifi页面进来的，如果是，重新连接socket，判断是否可用
    @Override
    protected void onResume() {
        super.onResume();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                t_type=0;
                String connectResult = TcpSocket.wificonnect();//wifi connect
                //show(connectResult);//TOast connect result
                if (isWifi()) {
                    if (me != null) {
                        if ((connectResult.equals("连接成功!")) || connectResult.equals("已经连接!")) {

                            me.setTitle("connect!");
                            me.setIcon(R.drawable.wifi_connect);
                        } else {

                            me.setTitle("no connect!");
                            me.setIcon(R.drawable.wifi_noconnect);
                        }
                    }
                } else {
                    if (me!=null){
                        me.setTitle("no connect!");
                        me.setIcon(R.drawable.wifi_noconnect);
                    }

                }
            }
        });
    }
    /**
     * 设置back监听
     */
    @Override
    public void onBackPressed() {
        exitApp();
    }
}
